// Call this from the developer console and you can control both instances
var calendars = {};
var selected_events = {};
var selectedTarget = null;

$(document).ready( function() {
    // Assuming you've got the appropriate language files,
    // clndr will respect whatever moment's language is set to.
    moment.locale('zh-cn');

    // Here's some magic to make sure the dates are happening this month.
    var thisMonth = moment().format('YYYY-MM');

    // The order of the click handlers is predictable. Direct click action
    // callbacks come first: click, nextMonth, previousMonth, nextYear,
    // previousYear, nextInterval, previousInterval, or today. Then
    // onMonthChange (if the month changed), inIntervalChange if the interval
    // has changed, and finally onYearChange (if the year changed).
    calendars.clndr = $('.cal').clndr({
		template: $('#full-clndr-template').html(),
        events: eventArray,
        clickEvents: {
            click: function (target) {
				selectedTarget = target;

				/*
				if(target.events.length) {
					selected_events = target.events;

					$('#appointment-form').attr('src', 
						'/manage/appointment-form/' + target.events[0].id + 
						'?hall-id=' + $('#appointment-form').data('hall-id') );
					$('#popupDelete')
						.data('appointment-id', target.events[0].id)
						.show();
				}
				*/

				if(target.events.length) {
					selected_events = target.events;
				}
				else {
					selected_events = {};
				}

				$('#form_save').hide();

				// refresh template
				calendars.clndr.render();
            },
        },
        multiDayEvents: {
            singleDay: 'date',
            endDate: 'endDate',
            startDate: 'startDate'
        },
        showAdjacentMonths: true,
        adjacentDaysChangeMonth: false,
		doneRendering: function() {
			if( selectedTarget != null )
				$(selectedTarget.element).css( { 'background': 'white' } ); 
		},
    });

    // Bind all clndrs to the left and right arrow keys
    $(document).keydown( function(e) {
        // Left arrow
        if (e.keyCode == 37) {
            calendars.clndr.back();
        }

        // Right arrow
        if (e.keyCode == 39) {
            calendars.clndr.forward();
        }
    });

	// Iframe loading
	$('.modal-body iframe').load( function() {  
		var self = this;
		var submit_button = $(self).contents().find('#form_save');
		submit_button.hide();
		$('#popupSave').click( function() {
			submit_button.click();
		});
	});

	$('#popupDelete')
		.click( function() {
			var msg = "确定要删除选中的预约信息吗？"; 
			if (confirm(msg)) { 
				$.get( '/manage/appointment-remove/' + $(this).data('appointment-id'),
					function() {
						location.reload();
					}
				);
			}
		})

	// Init
	$('.today').click();
});
